#!/usr/bin/env python
# -*- coding:utf8 -*-
# uncompyle6 version 2.15.1
# Python bytecode 2.7 (62211)
# Decompiled from: Python 2.7.10 (default, Jul  1 2017, 13:36:56) 
# [GCC 4.4.6 20110731 (Red Hat 4.4.6-4)]
# Embedded file name: ./paas/saas/models.py
# Compiled at: 2017-11-16 15:44:28
"""
Tencent is pleased to support the open source community by making 蓝鲸智云(BlueKing) available.
Copyright (C) 2017 THL A29 Limited, a Tencent company. All rights reserved.
Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License.
You may obtain a copy of the License at http://opensource.org/licenses/MIT
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and limitations under the License.
"""
import os, time, json
from django.db import models
from django.conf import settings
from django.core.files.storage import FileSystemStorage
from common.log import logger
from app.models import App
from app.constants import STATE_CHOICES_DISPALY_DICT
from saas.constants import SAAS_APP_LOGO_IMG_RELATED
APP_LOGO_IMG_RELATED = 'applogo'

class SaaSApp(models.Model):
    code = models.CharField(u'应用编码', max_length=30, unique=True, help_text=u'此处请用英文字母')
    name = models.CharField(u'应用名称', max_length=20)
    app = models.ForeignKey(to=App, blank=True, null=True, on_delete=models.CASCADE)
    current_version = models.ForeignKey(to='SaaSAppVersion', related_name='current_versions', blank=True, null=True)
    online_version = models.ForeignKey(to='SaaSAppVersion', related_name='online_versions', blank=True, null=True)
    created_time = models.DateTimeField(u'创建时间', auto_now_add=True, blank=True, null=True)
    logo = models.ImageField(upload_to=APP_LOGO_IMG_RELATED, blank=True, null=True)

    def _del_exist_file(self, name):
        _file = os.path.join(settings.MEDIA_ROOT, name)
        if os.path.exists(_file):
            os.remove(_file)

    def save(self, *args, **kwargs):
        """
        保存前修改 logo 存放路径
        """
        if not self.logo:
            return super(SaaSApp, self).save(*args, **kwargs)
        logo_ext = '.png'
        if self.logo.name.find('\\') >= 0:
            logo_name = APP_LOGO_IMG_RELATED + '\\' + str(self.code) + logo_ext
        else:
            if self.logo.name.find('/') >= 0:
                logo_name = APP_LOGO_IMG_RELATED + '/' + str(self.code) + logo_ext
            else:
                logo_name = APP_LOGO_IMG_RELATED + '/' + str(self.code) + logo_ext
        if cmp(logo_name, self.logo.name):
            logo_name = APP_LOGO_IMG_RELATED + '/' + str(self.code) + logo_ext
            self._del_exist_file(logo_name)
            self.logo.name = APP_LOGO_IMG_RELATED + '/' + str(self.code) + logo_ext
        super(SaaSApp, self).save(*args, **kwargs)

    @property
    def get_logo_url(self):
        if self.logo:
            return '%s?v=%s' % (self.logo.url, time.time())
        logo_name = '%s/%s.png' % (APP_LOGO_IMG_RELATED, self.code)
        logo_path = os.path.join(settings.MEDIA_ROOT, logo_name)
        if os.path.exists(logo_path):
            return '%s%s' % (settings.MEDIA_URL, logo_name)
        logo_name = '%s/%s.png' % (SAAS_APP_LOGO_IMG_RELATED, self.code)
        logo_path = os.path.join(settings.MEDIA_ROOT, logo_name)
        if os.path.exists(logo_path):
            return '%s%s' % (settings.MEDIA_URL, logo_name)
        return '%simg/app_logo/default.png' % settings.STATIC_URL

    @property
    def version(self):
        """
        应用的版本信息，如果无线上版本，则以当前版本为准
        """
        saas_version = self.online_version or self.current_version
        if saas_version:
            return saas_version.version
        return ''

    @property
    def creater(self):
        saas_version = self.online_version or self.current_version
        if not saas_version:
            return '--'
        return saas_version.get_settings().get('author', '--')

    @property
    def app_pro_url(self):
        return settings.APP_PROD_URL.format(app_code=self.code)

    @property
    def is_already_online(self):
        """
        应用是否已经上线
        """
        if self.app:
            return self.app.is_already_online
        return False

    @property
    def created_date_display(self):
        if not self.created_time:
            return self.created_time
        return self.created_time.strftime('%Y-%m-%d')

    @property
    def state(self):
        if not self.app:
            return 1
        return self.app.state

    @property
    def saas_state_display(self):
        if self.state == 1:
            return u'未部署'
        return STATE_CHOICES_DISPALY_DICT.get(self.state)

    def __unicode__(self):
        return self.code

    def __str__(self):
        return self.code

    class Meta:
        ordering = ('-code', )
        db_table = 'paas_saas_app'
        verbose_name = u'SaaS 应用'
        verbose_name_plural = u'SaaS 应用'


class SaaSAppVersion(models.Model):
    """
    SaaSVersion
    """
    version = models.CharField(u'版本', max_length=20)
    settings = models.TextField(u'包配置', blank=True, null=True)
    saas_app = models.ForeignKey(to='SaaSApp', blank=False, null=False, on_delete=models.CASCADE)
    upload_file = models.ForeignKey(to='SaaSUploadFile', blank=False, null=False)

    def get_settings(self):
        try:
            settings = json.loads(self.settings)
        except:
            settings = {}
            logger.exception(u'应用配置信息解析异常')

        return settings

    def __unicode__(self):
        return '%s %s %s' % (self.id, self.version, self.upload_file)

    def __str__(self):
        return '%s %s %s' % (self.id, self.version, self.upload_file)

    class Meta:
        db_table = 'paas_saas_app_version'
        verbose_name = u'SaaS 应用版本'
        verbose_name_plural = u'SaaS 应用版本'


class OverwriteStorage(FileSystemStorage):
    """
    overwrite the file on disk if the name is the same
    """

    def get_available_name(self, name):
        """Returns a filename that's free on the target storage system, and
        available for new content to be written to.
        
        Found at http://djangosnippets.org/snippets/976/
        """
        if self.exists(name):
            os.remove(os.path.join(settings.MEDIA_ROOT, name))
        return name


class SaaSUploadFile(models.Model):
    """
    SaaS上传安装包
    """
    name = models.CharField(u'文件名', max_length=100)
    size = models.IntegerField(u'文件大小', default=0, blank=True, null=True)
    md5 = models.CharField(u'md5', max_length=32, blank=False, null=False)
    file = models.FileField(u'文件', upload_to='saas_files', storage=OverwriteStorage())
    uploaded_at = models.DateTimeField(u'上传时间', auto_now_add=True, db_index=True)

    @property
    def url(self):
        return self.file.url

    def __unicode__(self):
        return self.name

    def __str__(self):
        return self.name

    class Meta:
        ordering = ('-uploaded_at', )
        db_table = 'paas_saas_upload_file'
        verbose_name = u'SaaS上传安装包'
        verbose_name_plural = u'SaaS上传安装包'
